import { base64 } from '@/libs'
import httpClient from '@/plugins/axios'
import { getConfig } from '@/settings'

/**
 * 通过密码模式获取访问令牌
 * @param {Object} params 令牌请求参数
 * @returns {Promise<Object>}
 */
export function obtainAccessToken(params) {
    const {
        oauth2: { client, endpoints },
    } = getConfig()
    const defaults = {
        grant_type: 'password',
    }
    const data = Object.assign({}, defaults, params)
    const encode = base64.encode(`${client.client_id}:${client.client_secret}`)
    const headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: `Basic ${encode}`,
    }
    return httpClient({
        url: endpoints.TOKEN_ENDPOINT,
        headers,
        method: 'post',
        data,
    })
}
